package dbUtil

import (
	"fmt"
	"gorm-demo/model"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var (
	GormClient *gorm.DB
)

func init() {
	fmt.Println("开始初始化")
	initClient()
	syncTable()
}

func initClient() {

	var logFile *os.File
	fileName := "dbOper.log"
	_, err2 := os.Stat(fileName)
	var fileErr error
	if err2 != nil {
		if os.IsNotExist(err2) {
			logFile, fileErr = os.Create(fileName)
			if fileErr != nil {
				fmt.Println("创建文件异常")
			}
		}
	} else {
		logFile, fileErr = os.OpenFile(fileName, os.O_APPEND, 6)
		if fileErr != nil {
			fmt.Println("打开文件异常")
		}
	}
	ormLog := logger.New(
		log.New(logFile, "\r", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // 禁用彩色打印
		},
	)
	var err error
	GormClient, err = gorm.Open(sqlite.Open("foo.db"), &gorm.Config{
		Logger: ormLog,
	})

	if err != nil {
		panic(err)
	}
}

func syncTable() {
	GormClient.AutoMigrate(&model.Person{})
}

func SelectAll() []model.Person {
	var arr []model.Person
	GormClient.Find(&arr)
	return arr
}

func AddPerson(person model.Person) int64 {
	return GormClient.Create(&person).RowsAffected
}
